// ==UserScript==
// @name         Bilibili视频自动跳过（片头片尾）
// @namespace    http://tampermonkey.net/
// @version      0.4
// @description  自动跳过视频开头和结尾指定时长，支持合集播放，支持UP主白名单
// @author       Your name
// @match        *://*.bilibili.com/video/*
// @grant        none
// ==/UserScript==

(function() {
  'use strict';

  // 设置要跳过的秒数
  const SKIP_START_SECONDS = 10; // 跳过片头时长（秒）
  const SKIP_END_SECONDS = 10;  // 跳过片尾时长（秒）
  
  // 设置UP主白名单（填入UP主的UID）
  const UP_WHITELIST = [
    '515688213',  // 示例UP主1
  ];

  // 存储事件监听器状态
  let currentVideo = null;
  let hasAttachedListeners = false;

  // 检查当前视频是否属于白名单UP主
  async function isWhitelistedUploader() {
    try {
      // 从URL中获取视频bvid
      const bvid = location.pathname.split('/')[2];
      // 调用B站API获取视频信息
      const response = await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`);
      const data = await response.json();
      
      if (data.code === 0) {
        const upUid = data.data.owner.mid.toString();
        const isWhitelisted = UP_WHITELIST.includes(upUid);
        console.log(`当前UP主UID: ${upUid}, 是否在白名单: ${isWhitelisted}`);
        return isWhitelisted;
      }
      return false;
    } catch (error) {
      console.error('获取UP主信息失败:', error);
      return false;
    }
  }

  async function attachVideoListeners(video) {
    if (!video || video === currentVideo) return;

    // 检查是否为白名单UP主
    const whitelisted = await isWhitelistedUploader();
    if (!whitelisted) {
      console.log('当前UP主不在白名单中，不进行跳过操作');
      return;
    }

    // 清除旧的事件监听器
    if (currentVideo) {
      currentVideo.removeEventListener('loadeddata', handleLoadedData);
      currentVideo.removeEventListener('play', handlePlay);
      currentVideo.removeEventListener('timeupdate', handleTimeUpdate);
    }

    currentVideo = video;
    hasAttachedListeners = true;

    // 添加新的事件监听器
    video.addEventListener('loadeddata', handleLoadedData);
    video.addEventListener('play', handlePlay);
    video.addEventListener('timeupdate', handleTimeUpdate);

    console.log('已添加视频事件监听器');
  }

  function handleLoadedData() {
      if (this.currentTime < SKIP_START_SECONDS) {
          this.currentTime = SKIP_START_SECONDS;
          console.log(`已自动跳过片头${SKIP_START_SECONDS}秒`);
      }
  }

  function handlePlay() {
      if (this.currentTime < SKIP_START_SECONDS) {
          this.currentTime = SKIP_START_SECONDS;
          console.log(`已自动跳过片头${SKIP_START_SECONDS}秒`);
      }
  }

  function handleTimeUpdate() {
      const remainingTime = this.duration - this.currentTime;
      if (remainingTime <= SKIP_END_SECONDS && remainingTime > 0) {
          const nextButton = document.querySelector('.bilibili-player-video-btn-next');
          if (nextButton) {
              console.log(`距离视频结束还有${remainingTime.toFixed(1)}秒，自动跳转下一集`);
              nextButton.click();
          } else {
              this.currentTime = this.duration;
              console.log('已跳过片尾');
          }
      }
  }

  function findAndAttachVideo() {
      const video = document.querySelector('.bpx-player-video-wrap video, .bilibili-player-video video');
      if (video && !hasAttachedListeners) {
          attachVideoListeners(video);
      }
  }

  // 使用定时器确保视频元素加载
  function initializeVideoCheck() {
      // 立即检查一次
      findAndAttachVideo();

      // 设置定期检查
      setInterval(() => {
          findAndAttachVideo();
      }, 1000); // 每秒检查一次
  }

  // 监听页面URL变化（用于合集播放切换视频时）
  let lastUrl = location.href;
  new MutationObserver(() => {
      if (location.href !== lastUrl) {
          lastUrl = location.href;
          console.log('检测到视频切换');
          hasAttachedListeners = false;
          findAndAttachVideo();
      }
  }).observe(document, {subtree: true, childList: true});

  // 页面加载完成后执行
  if (document.readyState === 'complete') {
      initializeVideoCheck();
  } else {
      window.addEventListener('load', initializeVideoCheck);
  }
})();
